<template>
  <el-card class="alloc-menu">
    <el-tree ref="menu-tree"
      :props="defaultProps"
      :data="menus"
      node-key="id"
      show-checkbox
      default-expand-all
      :default-checked-keys="checkedKeys"
      @check-change="handleCheckChange"
    >
    </el-tree>

    <div style="text-align: center">
        <el-button @click="resetChecked">清空</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
    </div>
  </el-card>
</template>

<script lang="ts">
import Vue from 'vue'
import { getMenuNodeList, allocateRoleMenus, getRoleMenus } from '@/services/menu'
import { Tree } from 'element-ui'
export default Vue.extend({
  name: 'AllocMenu',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },

  data () {
    return {
      menus: [],
      defaultProps: {
        label: 'name',
        children: 'subMenuList'
      },
      checkedKeys: []
    }
  },

  created () {
    this.loadMenus()
    this.loadRoleMenus()
  },

  methods: {
    async loadRoleMenus () {
      const { data } = await getRoleMenus(this.roleId)
      this.getcheckedKeys(data.data)
      console.log(data)
    },
    async loadMenus () {
      const { data } = await getMenuNodeList()
      this.menus = data.data
    },

    getcheckedKeys (menus: any) {
      menus.forEach((menu: any) => {
        if (menu.selected) {
          this.checkedKeys = [...this.checkedKeys, menu.id] as any
        }
        if (menu.subMenuList) {
          this.getcheckedKeys(menu.subMenuList)
        }
      })
    },

    resetChecked () {
      (this.$refs['menu-tree'] as Tree).setCheckedKeys([])
    },

    async onSave () {
      // 拿到选中的节点的数据Id
      const menuIdList = (this.$refs['menu-tree'] as Tree).getCheckedKeys()
      console.log(menuIdList)
      if (menuIdList.length === 0) {
        this.$message.warning('请选择菜单项')
        return
      }
      await allocateRoleMenus({
        roleId: this.roleId,
        menuIdList
      })
      this.$message.success('操作成功')
      this.$router.back()
    },

    handleCheckChange (data: any, checked: boolean, indeterminate: boolean) {
      console.log(data, checked, indeterminate)
    }
  }
})
</script>

<style lang="scss" scoped>
</style>
